<?php
namespace src;
use classlib\core\router;
use classlib\packer;
class Cminify {
	public function css() {
		$dir   = '/minify/css/';
		$ohash = substr(router::$uri, strlen($dir)-1);
		//验证Hash数值是否一直
		list($hash, $script) = explode(',', $ohash, 2);
		if (0 != strcasecmp(router::hash($script), $hash)) {
			return;
		}
		$script  = explode(',', $script);
		$basedir = \classlib\core\config::$appdir.'/view/static/';
		$nowsdir = $basedir;
		$packed  = array();
		foreach ($script as $file) {
			$file   = str_replace(';', '/', $file);
			$script = $nowsdir.$file.'.css';
			if (file_exists($script)) {
				$packed[] = "/* ".substr($script, strlen($basedir))." */\r\n".packer::packcss($script);
				$nowsdir  = dirname($script).'/';
				continue;
			}
			//到标准目录下检索文件
			if ($nowsdir != $basedir) {
				$script   = $basedir.$file.'.css';
				if (file_exists($script)) {
					$packed[] = "//".substr($script, strlen($basedir))."\r\n".packer::packcss($script);
					$nowsdir  = dirname($script).'/';
				}
			}
		}
		//如果是开发调试模式的话 不需要验证
		if (!OPENDEBUG) {
			$dir = WEBROOT.$dir;
			if (!is_dir($dir)) {
				mkdir($dir, 0777, true);
			}
			@file_put_contents($dir.$ohash.'.css', implode("\r\n", $packed));
		}
		header('Content-type: text/css');
		\classlib\web::cached();
		echo implode("\r\n", $packed);
	}
	
	public function js() {
		$dir   = '/minify/js/';
		$ohash = substr(router::$uri, strlen($dir)-1);
		//验证Hash数值是否一直
		list($hash, $script) = explode(',', $ohash, 2);
		if (0 != strcasecmp(router::hash($script), $hash)) {
			return;
		}
		$script  = explode(',', $script);
		$basedir = \classlib\core\config::$appdir.'/view/static/';
		$nowsdir = $basedir;
		$packed  = array();
		foreach ($script as $file) {
			$file   = str_replace(';', '/', $file);
			$script = $nowsdir.$file.'.js';
			if (file_exists($script)) {
				$packed[] = "//".substr($script, strlen($basedir))."\r\n".packer::packjs($script);
				$nowsdir  = dirname($script).'/';
				continue;
			}
			//到标准目录下检索文件
			if ($nowsdir != $basedir) {
				$script   = $basedir.$file.'.js';
				if (file_exists($script)) {
					$packed[] = "//".substr($script, strlen($basedir))."\r\n".packer::packjs($script);
					$nowsdir  = dirname($script).'/';
				}
			}
			
		}
		//如果是开发调试模式的话 不需要验证
		if (!OPENDEBUG) {
			$dir = WEBROOT.$dir;
			if (!is_dir($dir)) {
				mkdir($dir, 0777, true);
			}
			@file_put_contents($dir.$ohash.'.js', implode("\r\n", $packed));
		}
		header('Content-type: text/javascript');
		\classlib\web::cached();
		echo implode("\r\n", $packed);
	}
}